import React, {Component} from 'react';
import {Button, Card, Table, Modal, Tag, Radio, Form, Input, message, Upload, Select, Checkbox} from "antd";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {getCars, addCar, deleteCar, editCar} from "../../api/car";
import { getCarManager} from "../../api/carManager";
import axios from 'axios'

const { Option } = Select;

class Index extends Component {
    constructor(props){
        super(props);
        this.addFormRef = React.createRef();
        this.editFormRef = React.createRef();
        this.state = {
            total: 0,
            pageSize: 6,
            current: 1,
            pageSizeOptions: [6,8,10,12,14],
            loading: false,
            selectLoading: false,
            tableLoading: false,
            confirmLoading: false,
            imageUrl: '',
            carManagerIdList:[],
            filelist: [],
            dataSource: [],
            addIsVisible: false,
            editIsVisible: false,
            checked: false,
            columns: [
                {
                  title: '汽车编号',
                  dataIndex: 'key',
                  key: 'key'
                },
                {
                    title: '车牌号',
                    dataIndex: 'carNumber',
                    key: 'CarNumber'
                },
                {
                    title: '款式',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '管理员编号',
                    dataIndex: 'carmanagerId',
                    key: 'carmanagerId'
                },
                {
                    title: '车照',
                    dataIndex: 'carAvater',
                    key: 'carAvater',
                    render: (avater) => {
                        return avater?<img src={avater} style={{width: '50px',height: '40px'}} alt="加载中..."/>: <span>照片丢失</span>
                    }
                },
                {
                    title: '租金/小时',
                    dataIndex: 'price',
                    key: 'price'
                },
                {
                    title: '入库',
                    dataIndex: 'isUse',
                    key: 'isUse',
                    render: (isUse) => {
                        const color = isUse ? 'green': 'red';
                        const text = isUse ? '是': '否';
                        return <Tag color={color}>{text}</Tag>
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    render: (text,record,index) => {
                        return <Radio.Group size='default'>
                            <Button value='mod' onClick={this.editCar.bind(this,record)} type='primary'>编辑</Button>
                            <Button value='delete' onClick={this.deleteCar.bind(this,{text,record,index})} type='error'>{record.isUse ? '出库' : '入库'}</Button>
                        </Radio.Group>;
                    }
                }
            ],
            layout: {
                labelCol: {
                    span: 6,
                },
                wrapperCol: { span: 12 },
            },
            tailLayout: {
                wrapperCol: { span: 6, offset: 6},
            }
        }
    }

    //添加车辆
    addCar = async () => {
        await this.setState({
            addIsVisible: true,
            selectLoading: true
        })
        await getCarManager().then(res => {
            this.setState({
                carManagerIdList: res.data.map(item => {
                    return item.id;
                })
            })
        }).finally(() => {
            this.setState({
                selectLoading: false
            })
        })
    }

    //页码改变的回调
    paginationChange = (current,pageSize) => {
        this.setState({
            current,
            pageSize: pageSize
        })
    }

    //每页条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({
            current: 1,
            pageSize: size
        })
    }

    //取消添加车辆
    addCancel =() => {
        this.setState({
            addIsVisible: false,
            imageUrl: ''
        })
    }

    //确认添加车辆
    addOk = () => {
        this.setState({
            confirmLoading: true
        })
        this.addFormRef.current.setFieldsValue({
            isUse: this.state.checked
        })
        const data = this.addFormRef.current.getFieldsValue();
        addCar(data).then(res => {
            this.init();
            message.success(res.msg);
            this.addFormRef.current.setFieldsValue({
                carNumber: '',
                name: '',
                carmanagerId: '',
                carAvater: '',
                price: '',
                isUse: ''
            })
            this.setState({
                imageUrl: '',
                checked: false
            })
        }).catch(err => {
            message.error('车辆添加失败')
            this.setState({
                confirmLoading: false
            })
        }).finally(() => {
            this.setState({
                confirmLoading: false
            })
        })
    }

    //编辑车辆信息
    editCar = (record) => {
        const {key: id,carNumber, name, carAvater,carmanagerId,price,isUse} = record;
        this.setState({
            editIsVisible: true,
            imageUrl: carAvater,
            checked: isUse
        },() => {
            setTimeout(() => {
                this.editFormRef.current.setFieldsValue({
                    id,
                    name,
                    carNumber,
                    carmanagerId,
                    carAvater,
                    price,
                    isUse,
                })
            })
        })
    }

    //删除用户信息
    deleteCar = ({text,record,index}) => {
        deleteCar({isUse: record.isUse,id: record.key}).then(res => {
            message.success(res.msg);
            this.init();
        }).catch(err => {
            message.error('数据请求出错')
        })
    }

    //上传头像
    addUploadAvater = ({file}) => {
        const data = new FormData();
        data.append("Token","7d366bf734da5f49ba55a59bb242d5c273bf0911:Wqdd0F4QLwgsQmdrt-cnAKLD2g8=:eyJkZWFkbGluZSI6MTU4Njk1NTIxOCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzE1NjU1IiwiYWlkIjoiMTY3ODc2NSIsImZyb20iOiJmaWxlIn0=");
        data.append('file',file);
        this.setState({
            loading: true
        })
        axios.post("http://up.imgapi.com/",data).then(res => {
            this.setState({
                imageUrl: res.data.linkurl
            })
            this.addFormRef.current.setFieldsValue({
                carAvater: res.data.linkurl
            })
        }).finally(() => {
            this.setState({
                loading: false
            })
        })
    }

    editUploadAvater = ({file}) => {
        const data = new FormData();
        data.append("Token","7d366bf734da5f49ba55a59bb242d5c273bf0911:Wqdd0F4QLwgsQmdrt-cnAKLD2g8=:eyJkZWFkbGluZSI6MTU4Njk1NTIxOCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzE1NjU1IiwiYWlkIjoiMTY3ODc2NSIsImZyb20iOiJmaWxlIn0=");
        data.append('file',file);
        this.setState({
            loading: true
        })
        axios.post("http://up.imgapi.com/",data).then(res => {
            this.setState({
                imageUrl: res.data.linkurl
            })
            this.editFormRef.current.setFieldsValue({
                carAvater: res.data.linkurl
            })
        }).finally(() => {
            this.setState({
                loading: false
            })
        })
    }

    //上传前检验
    beforeUpload = (file) => {
        const limt = file.size/1024/1024 > 10;
        if (limt){
            message.error('文件大小超过10m,请重新选择');
            this.onRemove(file)
            return false;
        }
    }

    //删除不符合的文件
    onRemove = (fileList) => {
        this.setState({
            filelist: this.state.filelist.filter(item => {
                return item.name !== fileList.name
            })
        },() => {
            this.addFormRef.current.setFieldsValue({
                carAvater: '',
            })
        })
    }


    onChangeCheck = (e) => {
        this.setState({
            checked: e.target.checked
        })
    }

    //编辑取消
    editCancel = () => {
        this.setState({
            imageUrl: '',
            editIsVisible: false,
            checked: false
        })
    }

    //编辑信息提交
    editOk = () => {
        this.setState({
            confirmLoading: true
        })
        this.editFormRef.current.setFieldsValue({
            isUse: this.state.checked
        });
        const data = this.editFormRef.current.getFieldsValue();
        editCar(data).then(res => {
            message.success(res.msg);
            this.init();
        }).catch(err => {
            message.error('修改错误')
        }).finally(() => {
            this.setState({
                confirmLoading: false,
            })
        })
    }

    //初始化数据
    init = () => {
        getCars().then(res => {
            const dataSource = res.data.map(item => {
                return {
                    key: item.id,
                    carNumber: item.carNumber,
                    name: item.name,
                    carAvater: item.carAvater,
                    carmanagerId: item.carmanagerId,
                    price: item.price,
                    isUse: item.isUse
                }
            })
            this.setState({
                dataSource,
                total: res.data.length
            })
        })
    }

    componentDidMount() {
        this.init();
    }

    render() {
        const uploadButton = (
            <div>
                {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传头像</div>
            </div>
        );
        return (
            <Card title="车辆管理" className='mod_card' extra={<span><Button onClick={this.addCar} type='primary' style={{marginRight: 10}}>添加车辆</Button></span>}>
                <Table
                    dataSource={this.state.dataSource}
                    columns={this.state.columns}
                    pagination={{
                        total: this.state.total,
                        pageSize: this.state.pageSize,
                        showSizeChanger: true,
                        pageSizeOptions: this.state.pageSizeOptions,
                        showQuickJumper: true,
                        current: this.state.current,
                        onChange: this.paginationChange,
                        onShowSizeChange: this.onShowSizeChange
                    }}
                    loading={this.state.tableLoading}
                />
                <Modal
                    visible={this.state.addIsVisible}
                    title="添加车辆"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定添加"
                    cancelText="取消"
                    onCancel={this.addCancel}
                    onOk={this.addOk}
                >
                    <Form
                        {...this.state.layout}
                        name="add_car"
                        className="add_car"
                        ref={this.addFormRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label='车牌号'
                            name= 'carNumber'
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label= '款式'
                            name= 'name'
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="管理员编号"
                            name="carmanagerId"
                        >
                            <Select style={{ width: 120 }} loading={this.state.selectLoading}>
                                {
                                    this.state.carManagerIdList.map(item => {
                                        return <Option value={item} key={item}>{item}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label= "车牌"
                            name= 'carAvater'
                        >
                            <Upload
                                listType="picture-card"
                                showUploadList={false}
                                beforeUpload={this.beforeUpload}
                                onRemove={this.onRemove}
                                fileList={this.state.filelist}
                                customRequest={this.addUploadAvater}
                            >
                                {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="租赁/小时"
                            name="price"
                        >
                            <Input prefix="￥" suffix="RMB" />
                        </Form.Item>
                        <Form.Item
                            label="可用状态"
                            name="isUse"
                        >
                            <Checkbox onChange={this.onChangeCheck} checked={this.state.checked}>是/否</Checkbox>
                        </Form.Item>

                    </Form>
                </Modal>
                <Modal
                    visible={this.state.editIsVisible}
                    title="编辑车辆"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定"
                    cancelText="取消"
                    onCancel={this.editCancel}
                    onOk={this.editOk}
                >
                    <Form
                        {...this.state.layout}
                        name="edit_car"
                        className="edit_car"
                        ref={this.editFormRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label='汽车编号'
                            name= 'id'
                        >
                            <Input disabled/>
                        </Form.Item><Form.Item
                            label='车牌号'
                            name= 'carNumber'
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label= '款式'
                            name= 'name'
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="管理员Id"
                            name="carmanagerId"
                        >
                            <Select style={{ width: 120 }} loading={this.state.selectLoading}>
                                {
                                    this.state.carManagerIdList.map(item => {
                                        return <Option value={item} key={item}>{item}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label= "车牌"
                            name= 'carAvater'
                        >
                            <Upload
                                listType="picture-card"
                                showUploadList={false}
                                beforeUpload={this.beforeUpload}
                                onRemove={this.onRemove}
                                fileList={this.state.filelist}
                                customRequest={this.editUploadAvater}
                            >
                                {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="租赁/小时"
                            name="price"
                        >
                            <Input prefix="￥" suffix="RMB" />
                        </Form.Item>
                        <Form.Item
                            label="可用状态"
                            name="isUse"
                        >
                            <Checkbox onChange={this.onChangeCheck} checked={this.state.checked}>是/否</Checkbox>
                        </Form.Item>

                    </Form>
                </Modal>
            </Card>
        );
    }
}

export default Index;